#!/usr/bin/env python

import os, sys, subprocess, time, traci
import NetworkBuilder
from TLSController import TLSController
from NetworkBuilder import buildNetwork

###
## TODO parse command line
##
###

PORT = 8813
SUMO_EXE = "sumo-gui"
CONFIG_FILE = "../models/campinas/campinas.sumo.cfg"
NETWORK_FILE = "../models/campinas/campinas.net.xml"
STRATEGY = "adaptative"

def getSumoPath(exe) :
    sumoExe = exe
    
    if "SUMO" in os.environ:
        sumoExe = os.path.join(os.environ["SUMO"], "sumo-gui")
        
    return sumoExe

def startSumo(exe, configFile) :
    sumoProcess = subprocess.Popen("%s -c %s" % (exe, configFile), shell=True, stdout=sys.stdout)
    return sumoProcess

"""
" Inicializa o simulador e conecta com sua interface traci
"""
print "Controller strategy: %s"%(STRATEGY)

startSumo(getSumoPath(SUMO_EXE), CONFIG_FILE)
traci.init(PORT)

rsiNetwork = buildNetwork(NETWORK_FILE)
tlsControllers = {};

tlsIdList = traci.trafficlights.getIDList();

"""for tlsId in tlsIdList:"""
tlsControllers["campossalesxglicerio"] = TLSController(STRATEGY, "campossalesxglicerio", rsiNetwork);

traci.simulationStep(1);

for step in range(3000) :
    
    # O controlador adaptativo precisa executar em tempo real para que os algoritmos convirjam.
    if STRATEGY == "adaptative":
        time.sleep(0.3)
        
    traci.simulationStep(step)

    for tls in tlsControllers:
        tlsControllers[tls].onStep(step)

traci.close()
